<template>
  <div>
    <!-- 头部导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 角色列表区域 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
          <!-- 添加角色信息弹框 -->
          <el-dialog
            title="添加角色"
            :visible.sync="dialogVisible"
            width="50%"
            @close="closeBox"
          >
            <!-- 添加角色信息 -->
            <el-form :model="addRoles" ref="addFormRef" label-width="70px">
              <!-- //添加角色名称 -->
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addRoles.roleName"></el-input>
              </el-form-item>
              <!-- //添加角色描述 -->
              <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRoles.roleDesc"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <!-- 角色展示区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, id1) in scope.row.children"
              :key="id1"
              :class="['bdbox', 'vcenter']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 二、三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="(item2, id2) in item1.children"
                  :key="id2"
                  :class="['bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, id3) in item2.children"
                      :key="id3"
                      closable
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRightMes(scope.row)"
              >分配权限
            </el-button>
            <!-- 弹出的分配权限对话框 -->
            <el-dialog
              title="分配权限"
              :visible.sync="rightDialogVisible"
              width="50%"
              @close="setRightClose"
            >
              <!-- 树形控件 -->
              <el-tree
                :data="rightMessage"
                :props="treeProps"
                ref="treeRef"
                show-checkbox
                node-key="id"
              ></el-tree>
              <span slot="footer" class="dialog-footer">
                <el-button @click="rightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //角色列表数据
      rolesList: [],
      dialogVisible: false,
      //添加角色数据
      addRoles: {
        roleName: '',
        roleDesc: '',
      },
      //控制权限对话框的打开
      rightDialogVisible: false,
      //控制权限数据
      rightMessage: [],
      //树形控件属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      //默认选中控件的子节点Id
      defKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色数据失败')
      }

      this.rolesList = res.data
     // console.log(this.rolesList)
    },
    //监听角色添加框关闭事件，重置表单
    closeBox() {
      this.$refs.addFormRef.resetFields()
    },
    //添加角色
    addRole() {
      this.$refs.addFormRef.validate(async (val) => {
        if (!val) return //console.log(val)
        //可以发起添加网络用户的网络请求
        const { data: res } = await this.$http.post('roles', this.addRoles)
        //console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        //隐藏添加用户的对话框
        this.dialogVisible = false
        //刷新用户列表
        this.getRolesList()
      })
    },
    //设置权限对话框数据展示
    async showRightMes(role) {
      this.roleId = role.id
      //获取权限数据
      const { data: res } = await this.$http.get('rights/tree')
      //console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.rightMessage = res.data

      this.getLeafKey(role, this.defKeys)
      this.rightDialogVisible = true
    },
    //通过递归获取所有权限的ID
    getLeafKey(node, arr) {
      //如果当前节点不含children属性
      if (!node.children) {
        return arr.push(node.id)
      }
      //递归
      node.children.forEach((item) => {
        this.getRolesList(item, arr)
      })
    },
    //监听权限对话框关闭，清空选中默认子节点ID 
    setRightClose() {
      this.defKeys = []
    },
    //点击为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keys)

      const idStr = keys.join(',')
      console.log(idStr)

      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})
      console.log(res)
      // console.log(`roles/${this.roleId}/rights`)
      if(res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }

      this.$message.success("分配权限成功")
      this.getRolesList()
      this.rightDialogVisible = false
    },
    
  },
}
</script>

<style lang="less" scoped>
.el-button {
  margin-bottom: 12px;
}

.el-tag {
  margin: 7px;
}

.bdbox {
  border-bottom: 1px solid #eee;
}

.bdbox:nth-child(1) {
  border-top: 1px solid #eee;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdtop:nth-child(1) {
  border-top: none;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
